<?php
/**
 * CreateTime: 2022/5/30 15:50
 */

namespace App\Service\Lending;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ClientConsts\ClientAuditConsts;
use App\Consts\ClientConsts\ClientConsts;
use App\Consts\ContractConsts\ContractStatusConsts;
use App\Consts\ContractConsts\ContractSubTypeConsts;
use App\Consts\LendingConsts\LendingConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Contract\ContractModel;
use App\Models\Contract\ContractTypeModel;
use App\Models\LendingModel\LendingModel;
use App\Models\Staff\StaffModel;
use App\Service\MapService\ContractMapService;
use App\Service\MapService\DepartmentMapService;
use App\Service\MapService\StaffMapService;
use App\ServiceChecker\Contract\ContractLegitimacy;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Redis;

class LendingService
{
    private LendingModel $lendingModel;
    private $gcHelper;

    public function __construct()
    {
        $this->lendingModel = new LendingModel();
        $this->gcHelper = app()->gcHelper;
    }

    private function checkerAddLending($contractId){
        $cl = new ContractLegitimacy();
        $cl->verifyRecodeContractIsExists($contractId);
//        $this->gcHelper->checkerDictionaryHasNodesByParentKey(LendingConsts::LENDING_TYPE,$lendingType,"借阅类型错误");
    }

    public function addLending($data){
        $this->checkerAddLending($data['contract_id']);
        $currentInfo = TokenFuc::getCurrentStaffInfo();
        $defaultStatus = $this->gcHelper
            ->getDictionaryInfoByDictionaryKey(LendingConsts::LENDING_STATUS_STAY_AUDIT,[
                'dictionary_value'
            ])['dictionary_value'];
        $defaultLendingType = $this->gcHelper
            ->getDictionaryInfoByDictionaryKey(LendingConsts::LENDING_TYPE_DZ_1,[
                'dictionary_value'
            ])['dictionary_value'];
        // 写入默认值
        $data['lending_staff_id'] = $currentInfo['staff_id'];
        $data['lending_code'] = md5($data['contract_id'].$currentInfo['staff_id']);
        $data['lending_status'] = $defaultStatus;
        $data['borrow_time'] = $data['borrow_time'] ?? LendingConsts::LENDING_DEFAULT_TIME;
        $data['company_id'] = $currentInfo['company_id'];
        $data['lending_type'] = $defaultLendingType;
        unset($data['contract_name']);
        unset($data['archives_type_name']);
        $res = $this->lendingModel->addLending($data);
        if(!$res){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '借阅失败',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        return $res;
    }


	/* 获取合同档案的借阅资料库列表
	 *
	 */
	public function getLendingListEx($pageSize,$filters){
        $query =  new \App\Models\NewContract\ContractModel();
        $status = app()
            ->gcHelper
            ->getDictionaryInfoByDictionaryKey(ContractStatusConsts::CONTRACT_STATUS_RECORD,[
                'dictionary_value'
            ])['dictionary_value'];

        if($filters){

        }
        $res =  $query
            ->where('contract_status',$status)
            ->where('status',BaseConsts::STATUS_NORMAL)
            ->latest()
            ->Paginate($pageSize);
        if($res){
            $staffMs = new StaffMapService();
            $deptMs = new DepartmentMapService();
            $contractTypeM = new ContractTypeModel();
            $res = $res->toArray();
            foreach($res['data'] as $key => $value){
               $res['data'][$key]['contract_type_name'] =  $contractTypeM->getContractTypeInfo($value['contract_type_id'],["contract_type_name"])["contract_type_name"];
               $res['data'][$key]['contract_relative_name'] = $value['contract_name'];
               $res['data'][$key]['receive_name'] = $staffMs->staffMap($value['record_owner_id'],'staff_name');
               $res['data'][$key]['receive_department_name'] = $deptMs->deptMap($value['record_department_id'],'department_name');
               $res['data'][$key]['archives_origin_holder_id'] = $value['responsible_staff_id'];
               $res['data'][$key]['archives_origin_holder_name'] = $staffMs->staffMap($value['responsible_staff_id'],'staff_name');
               $res['data'][$key]['archives_origin_holder_department_id'] = $value['responsible_department_id'];
               $res['data'][$key]['archives_status'] = $value['contract_status'];
            }
        }

        return $res;


        return $this->lendingModel->getDataBankList($page);
	
	}
    public function getLendingList($pageSize,$page,$filters){
       
		//		$query = $this->lendingModel->select([
		//            'lending.lending_id',
		//            'lending.contract_id',
		//            'lending.lending_type',
		//            'lending.lending_staff_id',
		//            'lending.lending_audit_time',
		//            'lending.lending_time',
		//            'lending.lending_start_time',
		//            'lending.lending_code',
		//        ]);
		$query = $this->lendingModel->select(['*']);
        if($filters){
            $filters = json_decode($filters,true);
            if(isset($filters['lending_type']) && $filters['lending_type']){
                $query = $query->where('lending.lending_type',$filters['lending_type']);
            }
            if(isset($filters['lending_staff_id']) && $filters['lending_staff_id']){
                $query = $query->where('lending.lending_staff_id',$filters['lending_staff_id']);
            }
        }



        $res =  $this->lendingModel->getLendingList($query,$pageSize,$page)->toArray();
		
		#$this->gcHelper->gfDebugPrint($res);

		# test data
		#
		#
		#
		#
		//合同id
		//key
		//integer
		//contract_code
		//string
		//合同编号
		//contract_name
		//string
		//合同名称
		//contract_relative_name
		//string
		//合同材料名称
		//contract_relative_id
		//integer
		//合同材料id
		//contract_start_time
		//string
		//合同交接日期
		//lending_type
		//integer
		//档案类型id
		//archives_type_name
		//string
		//档案类型名称
		//archives_origin_holder_id
		//integer
		//原持有人id
		//archives_origin_holder_name
		//string
		//原持有人名称
		//archives_origin_holder_department_id
		//integer
		//原持有部门id
		//archives_origin_holder_department_name
		//string
		//原持有部门名称
		//archives_status
		//string
		//档案状态
		//receive_department_id
		//integer
		//接收部门id
		//receive_department_name
		//string
		//接收部门名称
		//receive_id
		//integer
		//接收人id
		//receive_name
		//string
		//接收人名称

		$res['data'][]	=	[
								'contract_id'	=> 1,
								'contract_code'	=> 'xxxx',
								'contract_name'	=> 'xxvvvvvvvvvvvvvv',
								'contract_relative_name'	=> 'sssssssssssssss',
								'contract_start_time'	=> '2022/6/11',
								'lending_type'	=> 12,
								'archives_type_name'	=> 'ssss',
								'archives_origin_holder_id'	=> 12,
								'archives_origin_holder_name'	=> 'sss12',
								'archives_origin_holder_department_id'	=> 12,
								'archives_status'	=> 'xxxxx12',
								'receive_department_id'	=>14,
								'receive_department_name'	=> 'xxxxx12',
								'receive_id'	=> 13,
								'receive_name'	=> 'xxxxx12',
							];
        foreach($res['data'] as $key => $value){
			
			$res['data'][$key] = $this->disposeData($value);
        }
		$o	= (object) $res;
		return
				[
					'total'			=> $o->total			,
					'current_page'	=> $o->current_page		,
					'data'			=> $o->data				,
				];
		//        return $res;
    }

    public function getLendingInfo($lendingId){
        $res =  $this->lendingModel->getLendingInfo($lendingId);
        return $this->disposeData($res);
    }

    private function disposeData($data){
        $contractModel = new ContractModel();
        $staffModel = new StaffModel();
        $contractName = @$contractModel->getContractInfo($data['contract_id'],['contract_name'])['contract_name'];
        $staffName = @$staffModel->getStaffDetail($data['lending_staff_id'],['staff_name'])['staff_name'];
        $data['contract_name']	= $contractName	==null?'':$contractName;
        $data['staff_name']		= $staffName	==null?'':$staffName;
        $data['archives_type_name'] = app()->gcHelper->getDictionaryMapValueByParentKey(
            LendingConsts::LENDING_TYPE,
            $data['lending_type']);
        return $data;
    }

    /**
     * 创建借阅命令审核通过后调用
     * @param $lendingId
     * @return mixed
     */
    public function touchLendingCommand($lendingId){
        // 生成校验口令
        $lendingInfo =  @$this->lendingModel->getLendingInfo($lendingId)->toArray();
        // 校验数据
        if(!$lendingInfo){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '借阅不存在',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }

        $lendingStatus = app()->gcHelper->getDictionaryInfoByDictionaryKey(LendingConsts::LENDING_STATUS_LENDING_NOW,[
            'dictionary_value'
        ])['dictionary_value'];

        if($lendingStatus != $lendingInfo['lending_status']){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                null,
                '借阅状态错误',
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        $commandKey = md5(time().$lendingInfo['lending_staff_id'].$lendingInfo['lending_time']);
        return Redis::setex($commandKey,$lendingInfo['lending_time'],$lendingInfo['lending_staff_id']);

    }
	public function archivesBorrowList($j){
		
		return $this->lendingModel->archivesBorrowList($j);
	}

    public function getLendingApplyInfo(int $lendingId)
    {
        $res =  $this->lendingModel->getLendingInfo($lendingId)->toArray();
        return $this->disposeData($res);
    }

    public function lendingRecord($pageSize,$filters)
    {
        $currentInfo = TokenFuc::getCurrentStaffInfo();
        $query = $this->lendingModel->select([
            'lending.lending_id',
            'lending.lending_id as key',
            'lending.company_id',
            'lending.contract_id',
            'lending.lending_type',
            'lending.lending_staff_id',
            'lending.lending_audit_time',
            'lending.borrow_time',
            'lending.lending_code',
            'lending.lending_start_time',
            'lending.lending_status',
            'lending.created_at',
            'contract.contract_name'
        ])
        ->leftJoin(TableConsts::CY_CONTRACT_TABLE_NAME." as contract",'contract.contract_id','lending.contract_id')
        ->where('lending.company_id',$currentInfo['company_id']);
        if($filters){
            if(isset($filters['contract_id']) && $filters['contract_id']){
                $query = $query->where('lending.contract_id',$filters['contract_id']);
            }
            if(isset($filters['contract_name']) && $filters['contract_name']){
                $query = $query->where('contract.client_name','LIKE',"%".$filters['contract_name']."%");
            }
            if(isset($filters['lending_staff_id']) && $filters['lending_staff_id']){
                $query = $query->where('lending.lending_staff_id',$filters['lending_staff_id']);
            }
            if(isset($filters['lending_status']) && $filters['lending_status']){
                $query = $query->where('lending.lending_status',$filters['lending_status']);
            }
        }
        return $this->extracted($query, $pageSize);
    }

    public function getSelfStaffLending(mixed $pageSize, mixed $filters)
    {
        $currentInfo = TokenFuc::getCurrentStaffInfo();
        $query = $this->lendingModel->select([
            'lending.lending_id',
            'lending.lending_id as key',
            'lending.company_id',
            'lending.contract_id',
            'lending.lending_type',
            'lending.lending_staff_id',
            'lending.lending_audit_time',
            'lending.borrow_time',
            'lending.lending_code',
            'lending.lending_start_time',
            'lending.lending_status',
            'lending.created_at',
            'contract.contract_name',
            'lending.lending_temporary_url'
        ])
        ->leftJoin(TableConsts::CY_CONTRACT_TABLE_NAME." as contract",'contract.contract_id','lending.contract_id')
        ->where('lending.lending_staff_id',$currentInfo['staff_id']);
        if($filters){
            if(isset($filters['contract_id']) && $filters['contract_id']){
                $query = $query->where('lending.contract_id',$filters['contract_id']);
            }
            if(isset($filters['contract_name']) && $filters['contract_name']){
                $query = $query->where('contract.client_name','LIKE',"%".$filters['contract_name']."%");
            }
            if(isset($filters['lending_status']) && $filters['lending_status']){
                $query = $query->where('contract.lending_status','LIKE',"%".$filters['lending_status']."%");
            }
        }
        return $this->extracted($query, $pageSize);
    }

    /**
     * @param $query
     * @param mixed $pageSize
     * @return array
     */
    private function extracted($query, mixed $pageSize): array
    {
        $res = $this->lendingModel->lendingRecord($query, $pageSize);
        if ($res) {
            $res = $res->toArray();
            $sms = new StaffMapService();
            foreach ($res['data'] as $key => $value) {
                $res['data'][$key]['lending_staff_name'] = $sms->staffMap($value['lending_staff_id'], 'staff_name');
            }
        }
        return $res;
    }
}